<?php

namespace app\admin\controller;

use app\models\{Region, User as Users, Address,Agent as Agents};
use think\Db;
use think\Validate;

class User extends Base
{

    public function index()
    {
        if ($this->request->isAjax()) {
            $model = new Users();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['nickName|mobile', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['type'])) {
                $where[] = ['type', '=',  $post['type']];
            }
            if (!empty($post['id'])) {
                $where[] = ['id', '=',  $post['id']];
            }
            if (!empty($post['mobile'])) {
                $user_id = (new Address())->where('mobile|name', $post['mobile'])->column('user_id') ?? [];
                $where[] = ['id', 'in',  $user_id];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $result) {
                $address = (new Address())->where('user_id', $result['id'])->order('is_default desc')->find() ?? [];
                if (!empty($address)) {
                    $address_name = getdrees($address['street'], 2);
                    $address['province_name'] = $address_name['province'];
                    $address['city_name'] = $address_name['city'];
                    $address['area_name'] = $address_name['area'];
                    $address['street_name'] = $address_name['street'];
                }
                $result['address'] = $address;
                //所属品牌
                $result['pinpai_name'] = (new Agents())->where('id',$result['agentid'])->value('nickname') ?? '';

            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }

    public function user_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'agentid' => 'require',
                'name' => 'require|chsAlphaNum|length:2,50',
                'mobile' => 'require'
            ], [
                'agentid.require' => '品牌不能为空',
                'name.require' => '姓名不能为空',
                'name.length' => '备注长度控制在2-50个字符',
                'name.chsAlphaNum' => '备注只能是汉字、字母和数字',
                'mobile.require' => '账号不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (empty($data['id']) && empty($data['password'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '密码必须填写']);
            }
            if (!empty($data['id']) && empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['password'])) {
                $data['yspassword'] = $data['password'];
                $data['password'] = md5(md5($data['password']));
            }
            $model = new Users();
            //查找店铺名称、账号是否已经被使用
            $haveshop = $model->where(['mobile' => $data['mobile'], 'status' => [1, 2]])->find();
            if (!empty($data['id'])) {
                if (!empty($haveshop) && $haveshop['id'] != $data['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                if (!empty($haveshop)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Users();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            return view('', [
                'row' => $row,
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }

    
    public function user_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new Users();
            $user = $model->where(['id' => $id])->find();
            if (empty($user)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'status':
                    $status = $user['status'] == 1 ? 2 : 1;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }
}
